import time,re
import pandas as pd
import redis
import pickle
import logging
import pywencai
import akshare as ak
import pandas as pd
import configparser
import datetime
from sqlalchemy import create_engine
import pymysql
import os
import traceback
from send_email import sendMessage
from 个股行业与概念涨幅分析 import get_brand_and_concept_rank



pymysql.install_as_MySQLdb()


log_format = "%(asctime)s - %(levelname)s - %(process)d - %(filename)s:%(lineno)d - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"  # 精确到秒
logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=date_format)

pid = os.getpid()
query_date = datetime.datetime.now().strftime('%Y%m%d')

# 日志文件路径
log_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'log/shouban/{pid}.log')

# 创建一个 handler，用于写入日志文件
file_handler = logging.FileHandler(log_file_path)
file_handler.setFormatter(logging.Formatter(log_format, date_format))
# 添加 handler 到 logger
logging.getLogger().addHandler(file_handler)

# 初始化配置解析器
config = configparser.ConfigParser()

# 读取配置文件
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
config.read(current_dir+'/config.ini', encoding='utf-8')


# 获取Redis的配置信息
redis_host = config.get('Redis', 'host')
redis_port = config.getint('Redis', 'port')
redis_db = config.getint('Redis', 'db')
redis_password = config.get('Redis', 'password')
r = redis.Redis(host=redis_host, port=redis_port, db=redis_db, password=redis_password)

mysql_port = config.getint('mysql', 'port')
mysql_host = config.get('mysql', 'host')
mysql_db = config.get('mysql', 'db')
import urllib.parse
mysql_password = urllib.parse.quote(config.get('mysql', 'password'))
mysql_user = config.get('mysql', 'user')
db_url = f'mysql://{mysql_user}:{mysql_password}@{mysql_host}:{mysql_port}/{mysql_db}'

engine = create_engine(db_url,pool_size=20,max_overflow=20,pool_recycle=60)


# subscriber = r.pubsub()
# subscriber.subscribe('bjzt_channel')

table = "real_market_info_tdx_h"


timestamp = "2024-04-19 09:31:00"
conceptName = "可燃冰"

# query_date = datetime.datetime.now().strftime('%Y-%m-%d')
datetime_obj = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
# 将datetime对象格式化为"YYYYMMDD"格式的字符串
formatted_date = datetime_obj.strftime("%Y%m%d")

print(formatted_date)

sql = f"select * from {table} rmd WHERE `timestamp`='{timestamp}'"

stock_info_df = pickle.loads(r.get(f"stock_panqian:{formatted_date}"))
tdx_df = pd.read_sql(sql, engine)

df = pd.merge(stock_info_df, tdx_df, how="inner", left_on="股票代码", right_on="code")

df = df[df['所属概念'].str.contains(conceptName, regex=False)]
df = df.sort_values(by="change", ascending=False)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
df["hs_change"] = round(100 * (df["price"] - df["open"]) / df["open"], 2)
df = df[["股票代码", "股票简称", "连续涨停天数", "change", "hs_change"]]
print(df)





